package cn.sylinx.hbatis.ext.proxy.command;

import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

import cn.sylinx.hbatis.kit.Tuple;

@SuppressWarnings("serial")
public class CommandProxy<T> implements InvocationHandler, Serializable {

	private final Class<T> commandInterface;

	public CommandProxy(Class<T> commandInterface) {
		this.commandInterface = commandInterface;
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

		MethodMetadata metadata = MethodMetadata.get(commandInterface, method);
		// Tuple[0]:查询参数, Tuple[1]:pageNumber, Tuple[2]:pageSize, Tuple[3]:datasource
		Tuple tuple = metadata.resove(args);
		return invokeInner(metadata, tuple);
	}

	private Object invokeInner(MethodMetadata metadata, Tuple tuple) {

		CommandInvokeHandler commandInvokeHandler = new CommandInvokeHandler(metadata,tuple);
		try {
			return commandInvokeHandler.invoke();
		} finally {
			commandInvokeHandler.releaseResource();
			commandInvokeHandler = null;
		}
	}
}
